package com.jwgf.fram;


import com.jwgf.common.AppContext;

import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class FramInterface {
    private static FramInterface instance;
    private static final String path = AppContext.getInstance().getFilesDir() + "/fram.bin";
    private static final int size = 32 * 1024;
    private static byte[] tempData = new byte[size];

    private FramInterface() {
        try {
            RandomAccessFile file = new RandomAccessFile(path, "rws");
            if (file.length() != size) {
                file.setLength(size);
            } else {
                file.read(tempData);
            }
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Observable.interval(2, TimeUnit.MINUTES)
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Throwable {
                        writeFile();
                    }
                });
    }

    public static FramInterface getInstance() {
        if (instance == null) {
            instance = new FramInterface();
        }
        return instance;
    }

    public synchronized void write(int startAddr, byte[] data) {
        System.arraycopy(data, 0, tempData, startAddr, data.length);
    }

    public byte[] read(int startAddr, int len) {
        byte[] data = new byte[len];
        System.arraycopy(tempData, startAddr, data, 0, len);
        return data;
    }

    public void writeFile() {
        synchronized (tempData) {
            try {
                RandomAccessFile file = new RandomAccessFile(path, "rws");
                file.seek(0);
                file.write(tempData);
                file.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public byte[] readFile(int startAddr, int len) {
        byte[] data = new byte[len];
        RandomAccessFile file = null;
        try {
            file = new RandomAccessFile(path, "rws");
            file.seek(startAddr);
            file.read(data);
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
